package com.example.project1;

import java.io.*;
import java.util.*;

public class StudentManager {
  private List<Student> students = new ArrayList<>();
  private static final String DATA_FILE = "./students.dat";

  // 添加学生
  public void addStudent(Student student) throws Exception {
    if (student == null) {
      throw new Exception("学生信息不能为空");
    }

    if (isIdExist(student.getId())) {
      throw new Exception("学号已存在");
    }

    students.add(student);
    System.out.println("添加成功: " + student);
  }

  // 删除学生
  public void deleteStudent(String id) throws Exception {
    Student student = findStudentById(id);
    if (student == null) {
      throw new Exception("学号不存在");
    }

    students.remove(student);
    System.out.println("删除成功: " + student);
  }

  // 修改学生信息
  public void updateStudent(String id, Student newStudent) throws Exception {
    Student oldStudent = findStudentById(id);
    if (oldStudent == null) {
      throw new Exception("学号不存在");
    }

    if (!id.equals(newStudent.getId()) && isIdExist(newStudent.getId())) {
      throw new Exception("新学号已存在");
    }

    int index = students.indexOf(oldStudent);
    students.set(index, newStudent);
    System.out.println("修改成功: " + newStudent);
  }

  // 查询所有学生
  public List<Student> getAllStudents() {
    return new ArrayList<>(students);
  }

  // 按学号查询
  public Student findStudentById(String id) {
    for (Student student : students) {
      if (student.getId().equals(id)) {
        return student;
      }
    }
    return null;
  }

  // 按姓名查询
  public List<Student> findStudentsByName(String name) {
    List<Student> result = new ArrayList<>();
    for (Student student : students) {
      if (student.getName().contains(name)) {
        result.add(student);
      }
    }
    return result;
  }

  // 按成绩排序
  public List<Student> sortByScore() {
    List<Student> sortedList = new ArrayList<>(students);
    Collections.sort(sortedList);
    return sortedList;
  }

  // 保存到文件
  public void saveToFile() throws IOException {
    try (ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream(DATA_FILE))) {
      oos.writeObject(students);
      System.out.println("数据已保存到文件: " + DATA_FILE);
    }
  }

  // 从文件加载
  @SuppressWarnings("unchecked")
  public void loadFromFile() throws IOException, ClassNotFoundException {
    File file = new File(DATA_FILE);
    if (!file.exists()) {
      System.out.println("数据文件不存在，将创建新文件");
      return;
    }

    try (ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream(DATA_FILE))) {
      students = (List<Student>) ois.readObject();
      System.out.println("从文件加载了 " + students.size() + " 条学生记录");
    }
  }

  // 检查学号是否存在
  private boolean isIdExist(String id) {
    return findStudentById(id) != null;
  }
}